package com.example.administrator.yanfoxconn.activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.Spinner;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.example.administrator.yanfoxconn.R;
import com.example.administrator.yanfoxconn.bean.CyCarMessage;
import com.example.administrator.yanfoxconn.bean.SelectModel;
import com.example.administrator.yanfoxconn.constant.Constants;
import com.example.administrator.yanfoxconn.constant.FoxContext;
import com.example.administrator.yanfoxconn.constant.ImageCaptureManager;
import com.example.administrator.yanfoxconn.intent.PhotoPickerIntent;
import com.example.administrator.yanfoxconn.intent.PhotoPreviewIntent;
import com.example.administrator.yanfoxconn.utils.BaseActivity;
import com.example.administrator.yanfoxconn.utils.FileUtil;
import com.example.administrator.yanfoxconn.utils.HttpConnectionUtil;
import com.example.administrator.yanfoxconn.utils.HttpUtils;
import com.example.administrator.yanfoxconn.utils.ImageZipUtils;
import com.example.administrator.yanfoxconn.utils.ToastUtils;
import com.example.administrator.yanfoxconn.widget.MyGridView;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

import org.json.JSONArray;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import androidx.annotation.Nullable;
import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * 物流消殺車輛 維護及提交界面
 * 共用 LP 協管-集中區放行，第一步提交照片
 *     LQ 安保部-高速放行
 */
public class JMCyKillActivity extends BaseActivity implements View.OnClickListener{
    private final int MESSAGE_TOAST = 2;
    private final int MESSAGE_GET_LIST = 1;//tv賦值
    private final int MESSAGE_NOT_NET = 3;//網絡問題

    private static final int REQUEST_CAMERA_CODE = 11;
    private static final int REQUEST_PREVIEW_CODE = 22;
    private ArrayList<String> imagePaths = null;//圖片未壓縮地址
    private ArrayList<String> imgZipPaths = new ArrayList<String>();//圖片壓縮后地址
    private ImageCaptureManager captureManager; // 相机拍照处理类

    @BindView(R.id.tv_title)
    TextView tvTitle;//標題
    @BindView(R.id.btn_title_left)
    Button btnBack;//返回
    @BindView(R.id.btn_title_right)
    Button btnUp;//提交

    @BindView(R.id.tl_all)
    TableLayout tlAll;
    @BindView(R.id.tv_down_ok)
    TextView tvDownOk;//可下車
    @BindView(R.id.tv_sq)
    TextView tvSq;//單號
    @BindView(R.id.tv_driver)
    TextView tvDriver;//司機
    @BindView(R.id.tv_tel)
    TextView tvTel;//聯繫方式
    @BindView(R.id.tv_car_num)
    TextView tvCarNum;//車牌號
    @BindView(R.id.tv_ma)
    TextView tvMa;//黃綠碼
    @BindView(R.id.tv_area)
    TextView tvArea;//区域

    @BindView(R.id.tr_tiwen)
    TableRow trTiWen;//體溫行
    @BindView(R.id.et_tiwen)
    EditText etTiWen;
    @BindView(R.id.tr_e_random)
    TableRow trERandom;//封號行 LQ
    @BindView(R.id.tv_e_random)
    TextView tvERandom;
    @BindView(R.id.btn_lq)
    Button btnLQ;//掃碼
    @BindView(R.id.tr_people_y_n)
    TableRow trPeopleYN;//個人防護行
    @BindView(R.id.tr_ma_y_n)
    TableRow trMaYN;//健康碼行
    @BindView(R.id.rb_y)
    RadioButton rbKeepY;//個人防護
    @BindView(R.id.rb_n)
    RadioButton rbKeepN;//個人防護
    @BindView(R.id.rb_car_y)
    RadioButton rbCarY;//健康碼

    @BindView(R.id.tr_photo)
    TableRow trPhoto;
    @BindView(R.id.tv_photo)
    TextView tvPhoto;
    @BindView(R.id.iv_empty)
    ImageView ivEmpty;//空白图片占位
    @BindView(R.id.gv_photo)
    MyGridView gridView;//图片显示区域
    private GridAdapter gridAdapter;
    private int photoNum=3;

    private String qrResult;//掃碼結果
    private String role,keep="Y",car="Y";//來向：cy 無體溫，cz 體溫不必須,jM 無體溫
    private CyCarMessage cyCarMessage;
    private List<CyCarMessage> cyCarMessageList;

    private String reason;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_jm_cy_kill);
        ButterKnife.bind(this);
        tvTitle.setText("消殺點檢");
        btnUp.setVisibility(View.VISIBLE);
        btnUp.setText("提交");
        btnUp.setOnClickListener(this);
        btnBack.setOnClickListener(this);
        ivEmpty.setOnClickListener(this);
        btnLQ.setOnClickListener(this);
        rbKeepY.setChecked(true);
        rbCarY.setChecked(true);
        rbKeepY.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                if (b){
                    keep="Y";
                }else{
                    keep="N";
                }
            }
        });

        rbCarY.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                if (b){
                    car="Y";
                }else{
                    car="N";
                }
            }
        });

        role = getIntent().getStringExtra("role");
        qrResult = getIntent().getStringExtra("id");

        if (role.equals("LP")){
            tlAll.setVisibility(View.GONE);
            getHMCarList();
            trPeopleYN.setVisibility(View.GONE);
            trMaYN.setVisibility(View.GONE);

        }else if (role.equals("LQ")){
            getHMCarList();
            trPeopleYN.setVisibility(View.GONE);
            trMaYN.setVisibility(View.GONE);
            trPhoto.setVisibility(View.GONE);
            trTiWen.setVisibility(View.VISIBLE);
            btnLQ.setVisibility(View.VISIBLE);
            btnUp.setVisibility(View.GONE);
        }else{
            getCarList();
        }
        int cols = getResources().getDisplayMetrics().widthPixels / getResources().getDisplayMetrics().densityDpi;
        cols = cols < 3 ? 3 : cols;
        gridView.setNumColumns(cols);

        // preview
        gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (position == imagePaths.size()) {
                    PhotoPickerIntent intent = new PhotoPickerIntent(JMCyKillActivity.this);
                    intent.setSelectModel(SelectModel.MULTI);
                    intent.setShowCarema(true); // 是否显示拍照
                    intent.setMaxTotal(photoNum); // 最多选择照片数量，默认为1
                    intent.setSelectedPaths(imagePaths); // 已选中的照片地址， 用于回显选中状态
                    startActivityForResult(intent, REQUEST_CAMERA_CODE);
                } else {
                    PhotoPreviewIntent intent = new PhotoPreviewIntent(JMCyKillActivity.this);
                    intent.setCurrentItem(position);
                    intent.setPhotoPaths(imagePaths);
                    startActivityForResult(intent, REQUEST_PREVIEW_CODE);
                }
            }
        });
    }
    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_title_left:
                finish();
                break;
            case R.id.iv_empty:
                PhotoPickerIntent intent = new PhotoPickerIntent(JMCyKillActivity.this);
                intent.setSelectModel(SelectModel.MULTI);
                intent.setShowCarema(true); // 是否显示拍照
                intent.setMaxTotal(photoNum); // 最多选择照片数量，默认为1
                intent.setSelectedPaths(imagePaths); // 已选中的照片地址， 用于回显选中状态

                startActivityForResult(intent, REQUEST_CAMERA_CODE);
                break;
            case R.id.btn_title_right:
                if(FoxContext.getInstance().getName().equals("")){
                    ToastUtils.showShort(this, "賬號異常，請重新登錄");
                } else if (imagePaths==null) {
                    ToastUtils.showShort(this, "請選擇圖片");
                }else{
                    if (role.equals("LP")){
                        normalHM2();
                    }else {
                        normal2();
                    }
                }
                break;
            case R.id.btn_lq:
                if (cyCarMessage.getFlag().equals("on")){
                    normalLQ(qrResult);
                }else{
                if (etTiWen.getText().toString().equals("")){
                    ToastUtils.showShort(JMCyKillActivity.this,"請填寫體溫！");
                }else{
                    Intent resultIntent = new Intent(JMCyKillActivity.this, QrCodeActivity.class);
                    resultIntent.putExtra("no", qrResult);
                    resultIntent.putExtra("num", "LQUP");
                    resultIntent.putExtra("tiwen",etTiWen.getText().toString());
                    startActivity(resultIntent);
                    finish();
                }}
                break;
        }
    }

    //普通車輛提交
    public void normal2() {
        Log.e("--------------------"," btnUp.setClickable(false);" +
                "");
        btnUp.setClickable(false);
        if (FoxContext.getInstance().getLoginId().equals("")) {
            ToastUtils.showShort(this, "登錄超時,請重新登陸");
        }
        final String url = Constants.HTTP_JM_CY_SAFEDATASAVE_SERVLET; //此處寫上自己的URL
        final Map<String, String> paramMap = new HashMap<String, String>(); //文本資料全部添加到Map裡
        showDialog();

        paramMap.put("xs_id", cyCarMessage.getItem());
        paramMap.put("xs_no", cyCarMessage.getFen_apply_no());
        paramMap.put("xs_recorder", FoxContext.getInstance().getLoginId());
        paramMap.put("e_safeguard", keep);
        paramMap.put("e_check", car);
        paramMap.put("e_order", cyCarMessage.getE_order());

        final Map<String, File> fileMap = new HashMap<String, File>(); //檔全部添加到Map裡

        for (int i = 0; i < imagePaths.size(); i++) {
            File pictureFile = new File(imagePaths.get(i)); //通過路徑獲取檔
//            fileMap.put("file" + i, pictureFile);//添加第一個文件
            final String pic_path = imagePaths.get(i);
            String sign_dir = Environment.getExternalStorageDirectory() + File.separator + "YanFoxconn" + File.separator + "Photos";
            String _path =  sign_dir + File.separator  + System.currentTimeMillis() +i+ ".jpg";
            //getFilesDir().getAbsolutePath()+"compressPic.jpg";
            //调用压缩图片的方法，返回压缩后的图片path
            final String compressImage = ImageZipUtils.compressImage(pic_path, _path, 80);
            final File compressedPic = new File(compressImage);
            imgZipPaths.add(i,compressImage);
            Log.e("----com---",compressImage);
            if (compressedPic.exists()) {
                Log.e("-------------","图片压缩上传");
                fileMap.put("file"+i,compressedPic);//添加第一個文件

            }else{//直接上传
                fileMap.put("file"+i,pictureFile);
            }
        }

        //開啟一個新執行緒，向伺服器上傳資料
        new Thread() {
            public void run() {
                try {

                    HttpURLConnection b = HttpConnectionUtil.doPostPicture(url, paramMap, fileMap);
                    Log.e("---------", "==fff===" + url);
                    if (b!=null){

                        Log.e("---------", "==fff===" + b);
                        if (b.getResponseCode()==200){
                            FileUtil.deletePhotos(JMCyKillActivity.this);
//                            delete(imagePaths);
                            Message message = new Message();
                            message.what = Constants.MESSAGE_UP;
                            message.obj = "上傳成功";
                            mHandler.sendMessage(message);
                            dismissDialog();
                        }else{
                            Message message = new Message();
                            message.what = Constants.MESSAGE_UP_FAIL;
                            message.obj = "上傳失敗";
                            mHandler.sendMessage(message);
                        }
                    }


                } catch (Exception e) {
                    e.printStackTrace();
                }finally {
                    FileUtil.deletePhotos(JMCyKillActivity.this);
                }
            }
        }.start();
    }
    //黃碼車輛提交
    public void normalHM2() {
        Log.e("--------------------"," btnUp.setClickable(false);" + "");
        btnUp.setClickable(false);
        if (FoxContext.getInstance().getLoginId().equals("")) {
            ToastUtils.showShort(this, "登錄超時,請重新登陸");
        }
        final String url = Constants.HTTP_JM_CY_LP_SAFEDATASAVE_SERVLET; //此處寫上自己的URL
        final Map<String, String> paramMap = new HashMap<String, String>(); //文本資料全部添加到Map裡
        showDialog();

        paramMap.put("xs_id", cyCarMessage.getItem());
        paramMap.put("xs_no", cyCarMessage.getFen_apply_no());
        paramMap.put("xs_recorder", FoxContext.getInstance().getLoginId());
        paramMap.put("e_safeguard", "");
        paramMap.put("e_check", "");
        paramMap.put("e_order", cyCarMessage.getE_order());

        Log.e("--------------------"," paramMap=="+paramMap.toString());
        final Map<String, File> fileMap = new HashMap<String, File>(); //檔全部添加到Map裡

        for (int i = 0; i < imagePaths.size(); i++) {
            File pictureFile = new File(imagePaths.get(i)); //通過路徑獲取檔
//            fileMap.put("file" + i, pictureFile);//添加第一個文件
            final String pic_path = imagePaths.get(i);
            String sign_dir = Environment.getExternalStorageDirectory() + File.separator + "YanFoxconn" + File.separator + "Photos";
            String _path =  sign_dir + File.separator  + System.currentTimeMillis() +i+ ".jpg";
            //getFilesDir().getAbsolutePath()+"compressPic.jpg";
            //调用压缩图片的方法，返回压缩后的图片path
            final String compressImage = ImageZipUtils.compressImage(pic_path, _path, 80);
            final File compressedPic = new File(compressImage);
            imgZipPaths.add(i,compressImage);
            Log.e("----com---",compressImage);
            if (compressedPic.exists()) {
                Log.e("-------------","图片压缩上传");
                fileMap.put("file"+i,compressedPic);//添加第一個文件

            }else{//直接上传
                fileMap.put("file"+i,pictureFile);
            }
        }

        //開啟一個新執行緒，向伺服器上傳資料
        new Thread() {
            public void run() {
                try {

                    HttpURLConnection b = HttpConnectionUtil.doPostPicture(url, paramMap, fileMap);
                    Log.e("---------", "==fff===" + url);
                    if (b!=null){

                        Log.e("---------", "==fff===" + b);
                        if (b.getResponseCode()==200){
                            FileUtil.deletePhotos(JMCyKillActivity.this);
//                            delete(imagePaths);
                            Message message = new Message();
                            message.what = Constants.MESSAGE_UP;
                            message.obj = "上傳成功";
                            mHandler.sendMessage(message);
                            dismissDialog();
                        }else{
                            Message message = new Message();
                            message.what = Constants.MESSAGE_UP_FAIL;
                            message.obj = "上傳失敗";
                            mHandler.sendMessage(message);
                        }
                    }


                } catch (Exception e) {
                    e.printStackTrace();
                }finally {
                    FileUtil.deletePhotos(JMCyKillActivity.this);
                }
            }
        }.start();
    }
    //LQ上高速提交
    private String url;//請求地址
    private String result;//返回結果

    private void normalLQ(String qrResult){
        String qr="";

        try {
            qr = URLEncoder.encode(URLEncoder.encode(qrResult, "UTF-8"), "UTF-8");

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        showDialog();
        url = Constants.HTTP_JM_CY_LP_SCAN_SEAL_SERVLET + "?no=" + qr+"&seals="+""+"&code="+FoxContext.getInstance().getLoginId()+"&flag="+"LQ_ON"+"&tiwen="+"";
        Log.e("-----","fff--"+url);
        new Thread() {
            @Override
            public void run() {
                result = HttpUtils.queryStringForPost(url);
                dismissDialog();
                Gson gson = new Gson();
                Log.e("---fff--result----", result.toString());
                if (result != null) {

                    JsonObject jsonObject = new JsonParser().parse(result).getAsJsonObject();
                    String errCode = jsonObject.get("errCode").getAsString();
                    if (errCode.equals("200")) {
//
//                        JsonArray array = jsonObject.get("data").getAsJsonArray();
//                        messageList = new ArrayList<AbnormalMessage>();
//
//                        for (JsonElement type : array) {
//                            AbnormalMessage humi = gson.fromJson(type, AbnormalMessage.class);
//                            messageList.add(humi);
//
//                        }
                        Message message = new Message();
                        message.what = MESSAGE_TOAST;
                        message.obj = "提交成功";
                        mHandler.sendMessage(message);


                    } else {
                        Log.e("--------", "dd=jsonObject.get(\"errMessage\").getAsString()==" + jsonObject.get("errMessage").getAsString());
//                                ToastUtils.showShort(RouteListActivity.this, jsonObject.get("errMessage").getAsString());
//                        Message message = new Message();
//                        message.what = 2;
//                        message.obj = jsonObject.get("errMessage").getAsString();
//                        mHandler.sendMessage(message);
                    }
                } else {
                    Message message = new Message();
                    message.what = MESSAGE_TOAST;
                    message.obj = "請求不成功";
                    mHandler.sendMessage(message);
//                    ToastUtils.showShort(QrCodeActivity.this, "請求不成功");
                }
            }
        }.start();
    }
    /**
     * 獲取車輛信息
     */

    public void getCarList() {
        String qr="";
        String url1="";
        final String[] result = {""};
        try {
            qr = URLEncoder.encode(URLEncoder.encode(qrResult, "UTF-8"), "UTF-8");

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        showDialog();
        url1 = Constants.HTTP_JM_CY_JUMP_SERVLET+"?no="+qr+"&role=JM";


        String finalUrl = url1;
        new Thread() {
            @Override
            public void run() {
                result[0] = HttpUtils.queryStringForPost(finalUrl);

                Log.e("---------", "=getcarLog=fff===" + finalUrl);
                Gson gson = new Gson();
                String response = result[0];
                Log.e("---------", "result==fff===" + response);
                cyCarMessageList = new ArrayList<CyCarMessage>();
                if (result[0] != null) {
                    JsonObject jsonObject = new JsonParser().parse(response).getAsJsonObject();
                    String errCode = jsonObject.get("errCode").getAsString();
                    if (errCode.equals("200")) {
                        JsonArray array = jsonObject.get("data").getAsJsonArray();

                        for (JsonElement type : array) {
                            CyCarMessage humi = gson.fromJson(type, CyCarMessage.class);
                            cyCarMessageList.add(humi);
                        }
                        Message message = new Message();
                        message.what = Constants.MESSAGE_SET_TEXT;
                        message.obj = jsonObject.get("errMessage").getAsString();
                        mHandler.sendMessage(message);
                    } else {
//                        isShowReturn = false;
                        Message message = new Message();
                        message.what = MESSAGE_TOAST;
                        message.obj = jsonObject.get("errMessage").getAsString();
                        mHandler.sendMessage(message);
                        cyCarMessageList.clear();
                    }
                } else {
                    Message message = new Message();
                    message.what = MESSAGE_TOAST;
                    message.obj = "無數據";
                    mHandler.sendMessage(message);
                }
                dismissDialog();
            }
        }.start();
    }
    /**
     * 黃碼獲取車輛信息
     */

    public void getHMCarList() {
        String qr="";
        String url1="";
        final String[] result = {""};
        try {
            qr = URLEncoder.encode(URLEncoder.encode(qrResult, "UTF-8"), "UTF-8");

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        showDialog();
        url1 = Constants.HTTP_JM_CY_LP_JUMP_SERVLET+"?no="+qr+"&role="+role;

        String finalUrl = url1;
        new Thread() {
            @Override
            public void run() {
                result[0] = HttpUtils.queryStringForPost(finalUrl);

                Log.e("---------", "=getcarLog=fff===" + finalUrl);
                Gson gson = new Gson();
                String response = result[0];
                Log.e("---------", "result==fff===" + response);
                cyCarMessageList = new ArrayList<CyCarMessage>();
                if (result[0] != null) {
                    JsonObject jsonObject = new JsonParser().parse(response).getAsJsonObject();
                    String errCode = jsonObject.get("errCode").getAsString();
                    if (errCode.equals("200")) {
                        JsonArray array = jsonObject.get("data").getAsJsonArray();

                        for (JsonElement type : array) {
                            CyCarMessage humi = gson.fromJson(type, CyCarMessage.class);
                            cyCarMessageList.add(humi);
                        }
                        Message message = new Message();
                        message.what = Constants.MESSAGE_SET_TEXT;
                        message.obj = jsonObject.get("errMessage").getAsString();
                        mHandler.sendMessage(message);
                    } else {
//                        isShowReturn = false;
                        Message message = new Message();
                        message.what = MESSAGE_TOAST;
                        message.obj = jsonObject.get("errMessage").getAsString();
                        mHandler.sendMessage(message);
                        cyCarMessageList.clear();
                    }
                } else {
                    Message message = new Message();
                    message.what = MESSAGE_TOAST;
                    message.obj = "無數據";
                    mHandler.sendMessage(message);
                }
                dismissDialog();
            }
        }.start();
    }

    Handler mHandler = new Handler() {
        @SuppressLint("HandlerLeak")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MESSAGE_TOAST://Toast彈出
                    ToastUtils.showShort(JMCyKillActivity.this,msg.obj.toString());
                    finish();
                    break;
                    case Constants.MESSAGE_UP_FAIL://Toast彈出
                    ToastUtils.showShort(JMCyKillActivity.this,msg.obj.toString());
                    break;
                case Constants.MESSAGE_UP://Toast彈出
                    if (role.equals("LP")){
                        finish();
                    }else{
                    getCarList();}
                    ToastUtils.showShort(JMCyKillActivity.this,msg.obj.toString());
                    break;
                case Constants.MESSAGE_NOT_NET:
                    ToastUtils.showLong(JMCyKillActivity.this, "網絡問題請退出重試!");

                    break;
                case Constants.MESSAGE_SET_TEXT:
                    cyCarMessage=cyCarMessageList.get(0);

                    if (role.equals("LP")){//協管-集中區放行
                        if (cyCarMessage.getUrl().equals("YOUX")){
                            tlAll.setVisibility(View.VISIBLE);
                            if (cyCarMessage.getMa().equals("綠碼")&&cyCarMessage.getYmok_flag().equals("Y")){
                                tvDownOk.setBackgroundResource(R.color.color_42D42B);
                                tvDownOk.setText("可下車");
                            }else {
                                tvDownOk.setBackgroundResource(R.color.color_d73d19);
                                tvDownOk.setText("不可下車");
                            }
                            tvSq.setText(cyCarMessage.getFen_apply_no());
                            tvDriver.setText(cyCarMessage.getDriver_name());
                            tvTel.setText(cyCarMessage.getDriver_tel());
                            tvCarNum.setText(cyCarMessage.getCar_num());
                            tvMa.setText(cyCarMessage.getMa());
                            tvArea.setText(cyCarMessage.getFactory_area());
                        }else if (cyCarMessage.getUrl().equals("YOUF")){
                            Intent resultIntent = new Intent(JMCyKillActivity.this, QrCodeActivity.class);
                            resultIntent.putExtra("no", qrResult);
                            resultIntent.putExtra("num", "LPUP");
                            resultIntent.putExtra("time",cyCarMessage.getInterval_time());
                            startActivity(resultIntent);
                            finish();
                        }else{
                            ToastUtils.showShort(JMCyKillActivity.this,"無車輛信息");
                            finish();
                        }
                    }else if(role.equals("LQ")){
                        tlAll.setVisibility(View.VISIBLE);
                        if (cyCarMessage.getMa().equals("綠碼")&&cyCarMessage.getYmok_flag().equals("Y")){
                            tvDownOk.setBackgroundResource(R.color.color_42D42B);
                            tvDownOk.setText("可下車");
                        }else {
                            tvDownOk.setBackgroundResource(R.color.color_d73d19);
                            tvDownOk.setText("不可下車");
                        }
                        tvSq.setText(cyCarMessage.getFen_apply_no());
                        tvDriver.setText(cyCarMessage.getDriver_name());
                        tvTel.setText(cyCarMessage.getDriver_tel());
                        tvCarNum.setText(cyCarMessage.getCar_num());
                        tvMa.setText(cyCarMessage.getMa());
                        tvArea.setText(cyCarMessage.getFactory_area());
                        if (cyCarMessage.getFlag().equals("on")){
                            trERandom.setVisibility(View.VISIBLE);
                            tvERandom.setText(cyCarMessage.getE_random());
                            trTiWen.setVisibility(View.GONE);
                            btnLQ.setText("放行");
                        }
                    }else{
                        tlAll.setVisibility(View.VISIBLE);
                        if (cyCarMessage.getUrl().equals("YOU")){
                            if (cyCarMessage.getMa().equals("綠碼")&&cyCarMessage.getYmok_flag().equals("Y")){
                                tvDownOk.setBackgroundResource(R.color.color_42D42B);
                                tvDownOk.setText("可下車");
                            }else {
                                tvDownOk.setBackgroundResource(R.color.color_d73d19);
                                tvDownOk.setText("不可下車");
                            }
                            tvSq.setText(cyCarMessage.getFen_apply_no());
                            tvDriver.setText(cyCarMessage.getDriver_name());
                            tvTel.setText(cyCarMessage.getDriver_tel());
                            tvCarNum.setText(cyCarMessage.getCar_num());
                            tvMa.setText(cyCarMessage.getMa());
                            tvArea.setText(cyCarMessage.getFactory_area());
                        }else{
                            Intent resultIntent = new Intent(JMCyKillActivity.this, WebViewTestActivity.class);
                            resultIntent.putExtra("url", cyCarMessage.getUrl()+FoxContext.getInstance().getLoginId());
                            resultIntent.putExtra("role", "JM");
                            startActivity(resultIntent);
                            finish();
                        }
                    }
                    break;
            }
            super.handleMessage(msg);
        }
    };

    @Override//圖片回傳
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                // 选择照片
                case REQUEST_CAMERA_CODE:
                    loadAdpater(data.getStringArrayListExtra(PhotoPickerActivity.EXTRA_RESULT));
                    break;
                // 预览
                case REQUEST_PREVIEW_CODE:
                    loadAdpater(data.getStringArrayListExtra(PhotoPreviewActivity.EXTRA_RESULT));
                    break;
                // 调用相机拍照
                case ImageCaptureManager.REQUEST_TAKE_PHOTO:
                    if (captureManager.getCurrentPhotoPath() != null) {
                        captureManager.galleryAddPic();

                        ArrayList<String> paths = new ArrayList<>();
                        paths.add(captureManager.getCurrentPhotoPath());
                        loadAdpater(paths);
                        Log.e("==========", paths.get(photoNum));
                    }
                    break;

            }
        }
    }
    //圖片賦值
    private void loadAdpater(ArrayList<String> paths) {
        if (imagePaths == null) {
            imagePaths = new ArrayList<>();
        }
        imagePaths.clear();
        imagePaths.addAll(paths);

        if (paths.size() > 0) {
            ivEmpty.setVisibility(View.GONE);
        } else {
            ivEmpty.setVisibility(View.VISIBLE);
        }

        try {
            JSONArray obj = new JSONArray(imagePaths);
            Log.e("--", obj.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }

        if (gridAdapter == null) {
            gridAdapter = new GridAdapter(imagePaths);
            gridView.setAdapter(gridAdapter);
            Log.e("----------------", "ddd==" + imagePaths.size());
        } else {
            gridAdapter.notifyDataSetChanged();
        }

    }
    private class GridAdapter extends BaseAdapter {
        private ArrayList<String> listUrls;

        public GridAdapter(ArrayList<String> listUrls) {
            this.listUrls = listUrls;
        }

        @Override
        public int getCount() {
            if (listUrls.size() == photoNum) {
                return photoNum;
            } else {
                return listUrls.size() + 1;
            }
        }

        @Override
        public String getItem(int position) {
            return listUrls.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ImageView imageView;
            if (convertView == null) {
                convertView = getLayoutInflater().inflate(R.layout.item_image, null);
                imageView = (ImageView) convertView.findViewById(R.id.imageView);
                convertView.setTag(imageView);
                // 重置ImageView宽高
//                LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(columnWidth, columnWidth);
//                imageView.setLayoutParams(params);
            } else {
                imageView = (ImageView) convertView.getTag();
            }
            if (position == listUrls.size()) {
                imageView.setImageBitmap(BitmapFactory.decodeResource(getResources(), R.mipmap.icon_addpic_unfocused));
                if (position == photoNum) {
                    imageView.setVisibility(View.GONE);
                }
            } else {
                Glide.with(JMCyKillActivity.this)
                        .load(new File(getItem(position)))
                        .placeholder(R.mipmap.default_error)
                        .error(R.mipmap.default_error)
                        .centerCrop()
                        .crossFade()
                        .into(imageView);
            }
            return convertView;
        }
    }
}
